<?php


namespace App\Services;


use App\Exceptions\OrderPaidException;
use App\Internals\UserInternal;
use EasyWeChat\Factory;
use function EasyWeChat\Kernel\Support\generate_sign;

class WxPayService
{
    private $app;
    private $config;

    public function __construct()
    {
        $this->config = config('wechat.payment');
        $this->app = Factory::payment($this->config);
        $this->app['cache'] = app('easyWechatCache');
    }


    public function createOrder($tradeNo, $userId, $name, $actualAmount)
    {
        $openId = UserInternal::getOpenId($userId);
        $result = $this->app->order->unify([
            'body' => '小狐英文绘本-' . $name,
            'out_trade_no' => $tradeNo,
            'total_fee' => (int)(bcmul($actualAmount, 100)), // 浮点数运算精读问题
            'notify_url' => $this->config['notify_url'],
            'trade_type' => 'JSAPI',
            'openid' => $openId,
        ]);
        if (empty($result['appid'])) {
            app('log')->error("订单创建失败: {$tradeNo}, {$userId}, {$actualAmount}");
            app('log')->error($result);
            throw new OrderPaidException();
        }
        $jsApiData = [
            'appId' => $result['appid'],
            'timeStamp' => (string)time(),
            'nonceStr' =>  uniqid(),
            'package' => 'prepay_id=' . $result['prepay_id'],
            'signType' => 'MD5',
        ];
        $jsApiData['paySign'] = generate_sign($jsApiData, $this->config['key']);
        $jsApiData['timestamp'] = $jsApiData['timeStamp'];
        unset($jsApiData['timeStamp']);
        return $jsApiData;
    }
}
